import axios from 'axios';

const AMAP_KEY = '09c8c233d3bed4c88860cfea851fc79b';
const AMAP_BASE_URL = 'https://restapi.amap.com/v3/config';
const CACHE_KEY = 'amap_district_data';
const CACHE_EXPIRE = 7 * 24 * 60 * 60 * 1000; // 缓存7天

/**
 * 获取缓存数据
 * @returns {Object|null}
 */
export const getCache = () => {
    const cacheData = localStorage.getItem(CACHE_KEY);
    if (!cacheData) return null;

    try {
        const { data, timestamp } = JSON.parse(cacheData);
        // 检查缓存是否过期
        if (Date.now() - timestamp > CACHE_EXPIRE) {
            localStorage.removeItem(CACHE_KEY);
            return null;
        }
        return data;
    } catch (e) {
        localStorage.removeItem(CACHE_KEY);
        return null;
    }
};

/**
 * 设置缓存数据
 * @param {Object} data
 */
export const setCache = (data) => {
    const cacheData = {
        data,
        timestamp: Date.now()
    };
    localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData));
};

/**
 * 获取省市区数据（优先从缓存读取）
 * @param {string} keywords 查询关键字
 * @param {string} subdistrict 子级行政区层级
 * @returns {Promise}
 */
export const getDistrict = async (keywords = '', subdistrict = 1) => {
    // 如果是查询中国地区数据，先尝试从缓存读取
    if (keywords === '中国' && subdistrict === 3) {
        const cache = getCache();
        if (cache) {
            return { data: cache };
        }
    }

    const response = await axios.get(`${AMAP_BASE_URL}/district`, {
        params: {
            key: AMAP_KEY,
            keywords,
            subdistrict,
            extensions: 'base'
        }
    });

    // 如果是中国地区数据且请求成功，存入缓存
    if (keywords === '中国' && subdistrict === 3 && response.data.status === '1') {
        setCache(response.data);
    }

    return response;
};

/**
 * 将高德地图返回的行政区数据转换为Element Plus Cascader需要的格式
 * @param {Array} districts 行政区数据
 * @returns {Array}
 */
export const transformDistrictData = (districts) => {
    if (!districts || !districts.length) return [];

    return districts.map(item => {
        const district = {
            value: item.name,
            label: item.name,
            level: item.level
        };

        if (item.districts && item.districts.length) {
            district.children = transformDistrictData(item.districts);
        }

        return district;
    });
};

/**
 * 清除地区数据缓存
 */
export const clearDistrictCache = () => {
    localStorage.removeItem(CACHE_KEY);
};

